package com.tpc.yaoxpt.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tpc.yaoxpt.main.LogModule;
import com.tpc.yaoxpt.main.MainController;
import com.tpc.yaoxpt.utils.FileUtil;
import com.tpc.yaoxpt.utils.HttpClientUtil;
import com.tpc.yaoxpt.utils.JDBCUtil;
import com.tpc.yaoxpt.utils.StringUtil;
import javafx.application.Platform;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DisOrderService {
    final LogModule logModule = LogModule.getInstance();
    public void disOrderService(){
        String intType = "C011";
        String intName = "配送订单";
        JSONObject jsonObject = new JSONObject();
        String url = FileUtil.getValue("PTCONFIG","URL");
        String table = FileUtil.getValue(intType,"TABLE");

        url = url + "v2/delv/drug/ship/commit";

        QueryRunner queryRunner = new QueryRunner();
        String sql = "select top 100  * from "+table+" where isdone = 'N' order by count  ";
        Connection connection = JDBCUtil.getConnection();
        try {
            List<Map<String, Object>> queryList = queryRunner.query(connection, sql, new MapListHandler());
            if(queryList.isEmpty()){
                return;
            }
            String jsonString = JSON.toJSONString(queryList);
            JSONObject jsonMain = new JSONObject();
            JSONObject requestJSON = new JSONObject();
            requestJSON.put("list", JSONArray.parseArray(jsonString));
            jsonMain.put("distributeInfo",requestJSON);
            log.info("业务请求参数："+StringUtil.getInString(intType,intName,jsonMain.toString()));
//            logModule.appendLogInfo( "\n" + StringUtil.getInString(intType,intName,jsonMain.toString()));
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    MainController.staticLogText.appendText("\n" + StringUtil.getInString(intType,intName,jsonMain.toString()));
                }
            });
            String returnInfo = HttpClientUtil.doPost(url, jsonMain);
//            logModule.appendLogInfo( "\n" + StringUtil.getOutString(intType,intName,returnInfo));
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    MainController.staticLogText.appendText("\n" +StringUtil.getOutString(intType,intName,returnInfo));
                }
            });
            log.info("业务返回参数："+ StringUtil.getOutString(intType,intName,returnInfo));
            JSONObject returnJSON = JSONObject.parseObject(returnInfo);
            if(returnJSON.getString("returnCode").equals("1")) {
                JSONArray successJSON = returnJSON.getJSONArray("successList");
                JSONArray errorJSON = returnJSON.getJSONArray("errorList");
                Object[][] updateSuccessObj = new Object[successJSON.size()][3];
                Object[][] updateErrorObj = new Object[errorJSON.size()][3];
                String updateSuccessSql = "update " + table + " set isdone = 'Y',count = 0 ,errorinfo = ? where companyDistributeId = ? and orderDetailId = ? ";
                String updateErrorSql = "update " + table + " set isdone = 'N',count = isnull(count,0)+1 ,errorinfo = ? where companyDistributeId = ? and orderDetailId = ? ";
                if (!successJSON.isEmpty()) {
                    for (int i = 0; i < successJSON.size(); i++) {
                        JSONObject oneJSON = successJSON.getJSONObject(i);
                        String companyDistributeId = oneJSON.getString("companyDistributeId");
                        String orderDetailId = oneJSON.getString("orderDetailId");
                        updateSuccessObj[i][0] = "";
                        updateSuccessObj[i][1] = companyDistributeId;
                        updateSuccessObj[i][2] = orderDetailId;
                    }
                    queryRunner.batch(connection, updateSuccessSql, updateSuccessObj);
                }
                if (!errorJSON.isEmpty()) {
                    for (int i = 0; i < errorJSON.size(); i++) {
                        JSONObject oneJSON = errorJSON.getJSONObject(i);
                        String companyDistributeId = oneJSON.getString("companyDistributeId");
                        String orderDetailId = oneJSON.getString("orderDetailId");
                        String errorInfo = oneJSON.getString("errorReasonList");
                        updateErrorObj[i][0] = errorInfo;
                        updateErrorObj[i][1] = companyDistributeId;
                        updateErrorObj[i][2] = orderDetailId;
                    }
                    queryRunner.batch(connection, updateErrorSql, updateErrorObj);
                }
            }else{
                String updateErrorSql = "update "+table+" set isdone = 'N',count = isnull(count,0)+1 ,errorinfo = ? where distributeId = ?  ";
                Object[][] updateErrorObj = new Object[JSONArray.parseArray(jsonString).size()][3];
                for(int i = 0 ; i< JSONArray.parseArray(jsonString).size();i++){
                    JSONObject oneJSON = JSONArray.parseArray(jsonString).getJSONObject(i);
                    String companyDistributeId = oneJSON.getString("companyDistributeId");
                    String orderDetailId = oneJSON.getString("orderDetailId");
                    String errorInfo = returnInfo;
                    updateErrorObj[i][0] = errorInfo;
                    updateErrorObj[i][1] = companyDistributeId;
                    updateErrorObj[i][2] = orderDetailId;
                }
                queryRunner.batch(connection,updateErrorSql,updateErrorObj);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBCUtil.close(connection);
        }

    }
}
